'''
Created on Jul 8, 2009

@author: mkiyer
'''

from optparse import OptionParser
import sys

def resolve_gene_aliases(genelist, hugo_names, alias_to_hugo):
    hugo_count = 0
    alias_count = 0
    non_mapping_count = 0
    
    for i, v in enumerate(genelist):
        allnames = v.strip().split()
        newnames = []
        for name in allnames:
            if name in hugo_names:
                hugo_count += 1
                newnames.append(name)
            elif name in alias_to_hugo:
                alias_count += 1
                newnames.append(alias_to_hugo[name])
            else:
                non_mapping_count += 1
                newnames.append(name)
        print ' '.join(newnames)

    print >>sys.stderr, 'hugo count:', hugo_count
    print >>sys.stderr, 'alias count:', alias_count
    print >>sys.stderr, 'non mapping count:', non_mapping_count

def parse_entrez_gene_db(genedbfhd):
    alias_dict = {}
    hugo_names = set([])
    for thisline in genedbfhd:
        fields = thisline.strip().split('\t')
        hugoname = fields[2]
        aliases = fields[4].split('|')
        for alias in aliases:
            alias_dict[alias] = hugoname
        hugo_names.add(hugoname)
    return hugo_names, alias_dict

if __name__ == '__main__':

    # setup command line parser    
    optparser = OptionParser()
    optparser.add_option('--db', dest="db",
                         help="entrez gene database table file")
    # parse command line
    (options, args) = optparser.parse_args()
    # check options, args
    if len(args) < 1:
        optparser.error('No input file specified')
    if not options.db:
        optparser.error('No entrez db file specified')
    
    # get arguments
    entrez_gene_file = options.db
    genelistfile = args[0]
    
    # resolve aliases
    hugo_names, alias_to_hugo = parse_entrez_gene_db(open(entrez_gene_file))
    resolve_gene_aliases(open(genelistfile, 'rU'), hugo_names, alias_to_hugo)